window.CP_TABLE = {};
window.CP_TABLE_LIST = [];
window.NOW_FIGURE = 4 //4个位， 3十位...
window.NOW_SHOW_ROW_NUM = 50;
window.CP_QS = 1;
window.CP_INDEX = 0;
window.CP_STEP_LEN = 9;
window.NOW_RANGE_TYPE = "0";
window.RANGE_OBJ = {
	"0" : order_by_asc,
	"1" : order_by_last_row_sync,
	"2" : order_by_compare_sync,
	"3" : order_by_pairs_last_row_sync,
	"4" : order_by_pairs_compare_sync
};
window.CP_COMPARE_LIST = [];
window.HAS_SHOW_LOADING = false;
window.COL_TAG = {};
window.FINAL_MATRIX;
window.COMPARE_MATRIX;
window.TABLE_TITLE = [];
window.ORDER_INDEX = [];

var fs = require("fs");
var EventProxy = require('eventproxy');
var exec = require('child_process').exec;
var Worker = require('webworker-threads').Worker;
var storage_dir_path = process.env["appdata"] + path.sep + "cpycxt";
var storage_file_path = storage_dir_path + path.sep + "save.dat";
var import_exe_path = process.cwd() + path.sep + "util" + path.sep + "import_util.exe";

var table_show_row = 11;
var table_show_col = 25 + 6;
var now_table_row = 0;
var now_table_col = 0;

function modify_check_access(flag) {
	var str = fs.readFileSync(storage_file_path);
	var obj = JSON.parse(str);
	obj["flag"] = flag;
	fs.writeFileSync(storage_file_path, JSON.stringify(obj));
}

function get_cp_qs(){
	if(window.CP_QS <= 0) {
		window.CP_QS = 1;
	}
	var date = new Date();
	var day = date.format("dd-");
	var qs = S("" + window.CP_QS).padLeft(3, '0');
	// window.CP_QS = window.CP_QS + 1;
	return day + qs;
}

function hideLoading() {
	window.HAS_SHOW_LOADING = false;
	$("#page_loading").fadeOut(200);
	$("#progress_center").fadeOut(200);
}

function showLoading() {
	window.HAS_SHOW_LOADING = true;
	$("#page_loading").show();
	$("#progress_center").show();
}


function create_table_row(obj) {
	var tr = $("<tr />").appendTo("tbody");
	var td_qs = $("<td/>").appendTo(tr);
	var a = $("<a/>").attr({
		"id": obj["ID"],
		"qs": obj["QS"],
		"win_num": obj["WIN_NUM"],
		"table_index": obj["TABLE_INDEX"],
		"href": "#",
		"class": "qs_operate"
	}).html(obj["QS"]).appendTo(td_qs);
	var td_win_num = $("<td/>").appendTo(tr).html(obj["WIN_NUM"]);
	var td_big = $("<td/>").appendTo(tr);
	var td_small = $("<td/>").appendTo(tr);
	var big_or_small = (Number)(obj["BIG_OR_SMALL"]);
	if(big_or_small === 0) {
		window.COL_TAG["big_temp"]++;
		if(window.COL_TAG["small"] < window.COL_TAG["small_temp"] + 1) {
			window.COL_TAG["small"] = window.COL_TAG["small_temp"] + 1;
		} 
		window.COL_TAG["small_temp"] = 0;
		var big_tag = (Number)($("tbody tr:last-child td").eq(2).attr("tag"));
		if(big_tag) {
			big_tag = big_tag + 1;
		} else {
			big_tag = 1;
		}
		td_big.append($("<div/>").addClass("wrong_div").html("" + big_tag)).attr({"tag": big_tag});
		td_small.append($("<div/>").addClass("correct_div")).attr({"tag": 0});

	} else {
		window.COL_TAG["small_temp"]++;
		if(window.COL_TAG["big"] < window.COL_TAG["big_temp"] + 1) {
			window.COL_TAG["big"] = window.COL_TAG["big_temp"] + 1;
		} 
		window.COL_TAG["big_temp"] = 0;
		td_big.append($("<div/>").addClass("correct_div")).attr({"tag": 0});
		var small_tag = (Number)($("tbody tr:last-child td").eq(3).attr("tag"));
		if(small_tag) {
			small_tag = small_tag + 1;
		} else {
			small_tag = 1;
		}
		td_small.append($("<div/>").addClass("wrong_div").html("" + small_tag)).attr({"tag": small_tag});
	}
	var td_odd = $("<td/>").appendTo(tr);
	var td_even = $("<td/>").appendTo(tr);
	var parity = (Number)(obj["PARITY"]);
	if(parity === 0) {
		window.COL_TAG["odd_temp"]++;
		if(window.COL_TAG["even"] < window.COL_TAG["even_temp"] + 1) {
			window.COL_TAG["even"] = window.COL_TAG["even_temp"] + 1;
		} 
		window.COL_TAG["even_temp"] = 0;
		var odd_tag = (Number)($("tbody tr:last-child td").eq(4).attr("tag"));
		if(odd_tag) {
			odd_tag = odd_tag + 1;
		} else {
			odd_tag = 1;
		}
		td_odd.append($("<div/>").addClass("wrong_div").html("" + odd_tag)).attr({"tag": odd_tag});
		td_even.append($("<div/>").addClass("correct_div")).attr({"tag": 0});
	} else {
		window.COL_TAG["even_temp"]++;
		if(window.COL_TAG["odd"] < window.COL_TAG["odd_temp"] + 1) {
			window.COL_TAG["odd"] = window.COL_TAG["odd_temp"] + 1;
		} 
		window.COL_TAG["odd_temp"] = 0;
		td_odd.append($("<div/>").addClass("correct_div")).attr({"tag": 0});
		var even_tag = (Number)($("tbody tr:last-child td").eq(5).attr("tag"));
		if(even_tag) {
			even_tag = even_tag + 1;
		} else {
			even_tag = 1;
		}
		td_even.append($("<div/>").addClass("wrong_div").html("" + even_tag)).attr({"tag": even_tag});
	}
	var compare = JSON.parse(obj["COMPARE"].toString());
	for(var i in window.CP_TABLE_LIST) {
		var val = window.CP_TABLE_LIST[i];
		var td = $("<td>");
		//var sign = $("<div/>").addClass("sign").html(val).appendTo(td);
		//var tag = $("<div/>").addClass("sign_tag").appendTo(td);
		var sign_div = $("<div/>").appendTo(td);
		td.attr("tag", compare[val]);
		if(!compare[val] || compare[val] === 0) {
			//tag.css({"background-color": "green"});
			sign_div.addClass("correct_div");
		} else {
			sign_div.addClass("wrong_div").html(compare[val]);
		}
		tr.append(td);
	}
	a.click(function(){
		var id = $(this).attr("id");
		gDialog.fCreate({title:'修改窗口',url:'modify.ahtml',width:500}).show();
		$("#qs_modify").val($(this).attr("qs"));
		$("#win_num_modify").val($(this).attr("win_num")).attr({
			"cp_id": id,
			"table_index": $(this).attr("table_index")
		});
	});	
	// return tr;
}

function refresh_table_UI() {
	console.log(new Date().format("yyyyMMdd HH:mm:ss"));
	$("tbody").empty();
	get_cp_trend_by_figure(window.NOW_FIGURE, window.NOW_SHOW_ROW_NUM, function(err, list) {
		if(err) {
			gDialog.fAlert('读取数据错误：' + err.message);
			return;
		}
		var show_loading_flag = list.length > 0;
		if(show_loading_flag) {
			showLoading();
		}
		window.CP_COMPARE_LIST = list;
		for(var i = 0; i < window.CP_COMPARE_LIST.length; i++) {
			setTimeout(function(index){
				create_table_row(window.CP_COMPARE_LIST[index]);
				//var tr = create_table_row(window.CP_COMPARE_LIST[index]);
				// $("tbody").append(tr);
				// $('#progressbar').progressbar('stepIt');
				if(index === window.CP_COMPARE_LIST.length - 1) {
					setTimeout(function(){
						//refresh_compare();
						hideLoading();
						console.log(new Date().format("yyyyMMdd HH:mm:ss"));
						adjust_col();
					}, 100);
				}
			}, 0, i);
			// var tr = create_table_row(window.CP_COMPARE_LIST[i]);
			// $("tbody").append(tr);
		}
		
	});
}

function refresh_new_compare_sync() {
	window.COMPARE_MATRIX = [];
	var row_len = window.FINAL_MATRIX.length;
	if(row_len <= table_show_row) {
		return;
	}
	var compare_matrix = [];
	for(var i = 2; i < 258; i++) {
		var item_arr = [];
		for(var j = row_len - 1; j >= row_len - window.CP_STEP_LEN; j--) {
			var tag = window.FINAL_MATRIX[j][i];
			item_arr.push(tag);
		}
		compare_matrix.push(item_arr);
	}
	for(var i = 2; i < 258; i++) {
		var count = 0;
		var row_index = row_len - window.CP_STEP_LEN - 1;
		var index = 0;
		while(true) {
			if((window.FINAL_MATRIX[row_index][i] > 0 && compare_matrix[i - 2][index] > 0) 
				|| (window.FINAL_MATRIX[row_index][i] == 0 && compare_matrix[i - 2][index] == 0)) {
				count++;
				index++;
				if(index === window.CP_STEP_LEN) {
					index = 0;
				}
				row_index--;
				if(row_index < 0) {
					break;
				}
			} else {
				break;
			}
		}
		window.COMPARE_MATRIX.push(count);
	}

}

function order_by_asc() {
	window.ORDER_INDEX = [];
	for(var i = 2; i < 258; i++) {
		window.ORDER_INDEX.push(i);
	}
}

function order_by_compare_sync() {
	window.ORDER_INDEX = [];
	var temp_list = [];
	for(var i = 0; i < window.COMPARE_MATRIX.length; i++) {
		var begin_val = window.COMPARE_MATRIX[i];
		if(i == 0) {
			temp_list.push(begin_val);
			window.ORDER_INDEX.push(i + 2);
		} else {
			var flag = false;
			for (var j in temp_list) {
				if(begin_val > temp_list[j]){
					flag = true;
					temp_list.splice(j, 0, begin_val);
					window.ORDER_INDEX.splice(j, 0, i + 2);
					break;
				}
			}
			if(!flag) {
				temp_list.push(begin_val);
				window.ORDER_INDEX.push(i + 2);
			}
		}
	}
	console.log(temp_list);
	console.log(window.ORDER_INDEX);
}

function order_by_last_row_sync() {
	window.ORDER_INDEX = [];
	var temp_list = [];
	for(var i = 2; i < 258; i++) {
		var begin_val = window.FINAL_MATRIX[window.FINAL_MATRIX.length - 1][i];
		if((Number)(i) === 2) {
			temp_list.push(begin_val);
			window.ORDER_INDEX.push(i);
		} else {
			var flag = false;
			for (var j in temp_list) {
				if(begin_val > temp_list[j]){
					flag = true;
					temp_list.splice(j, 0, begin_val);
					window.ORDER_INDEX.splice(j, 0, i);
					break;
				}
			}
			if(!flag) {
				temp_list.push(begin_val);
				window.ORDER_INDEX.push(i);
			}
		}
	}
	console.log(temp_list);
	console.log(window.ORDER_INDEX);
}

function order_by_pairs_last_row_sync(){
	window.ORDER_INDEX = [];
	var temp_list = [];
	for(var i = 6; i < 132; i++) {
		var begin_val1 = window.FINAL_MATRIX[window.FINAL_MATRIX.length - 1][i];
		var begin_val2 = window.FINAL_MATRIX[window.FINAL_MATRIX.length - 1][258 - i + 5];
		var begin_val = Math.max(begin_val1, begin_val2);
		if(temp_list.length == 0) {
			temp_list.push(begin_val);
			window.ORDER_INDEX.push(i);
			window.ORDER_INDEX.push(258 - i + 5);
		} else {
			var flag = false;
			for (var j in temp_list) {
				if(begin_val > temp_list[j]){
					flag = true;
					temp_list.splice(j, 0, begin_val);
					window.ORDER_INDEX.splice(j * 2, 0, i);
					window.ORDER_INDEX.splice(j * 2 + 1, 0, 258 - i + 5);
					break;
				}
			}
			if(!flag) {
				temp_list.push(begin_val);
				window.ORDER_INDEX.push(i);
				window.ORDER_INDEX.push(258 - i + 5);
			}
		}
	}
	for(var i = 2; i < 6; i = i + 2) {
		var begin_val1 = window.FINAL_MATRIX[window.FINAL_MATRIX.length - 1][i];
		var begin_val2 = window.FINAL_MATRIX[window.FINAL_MATRIX.length - 1][i + 1];
		var begin_val = Math.max(begin_val1, begin_val2);
		var flag = false;
		for (var j in temp_list) {
			if(begin_val > temp_list[j]){
				flag = true;
				temp_list.splice(j, 0, begin_val);
				window.ORDER_INDEX.splice(j * 2, 0, i);
				window.ORDER_INDEX.splice(j * 2 + 1, 0, i + 1);
				break;
			}
		}
		if(!flag) {
			temp_list.push(begin_val);
			window.ORDER_INDEX.push(i);
			window.ORDER_INDEX.push(i + 1);
		}
	}
	console.log(temp_list);
	console.log(window.ORDER_INDEX);
}

function order_by_pairs_compare_sync() {
	window.ORDER_INDEX = [];
	var temp_list = [];
	for(var i = 4; i < 130; i++) {
		var begin_val1 = window.COMPARE_MATRIX[i];
		var begin_val2 = window.COMPARE_MATRIX[256 - i + 3];
		var begin_val = Math.max(begin_val1, begin_val2); 
		if(temp_list.length == 0) {
			temp_list.push(begin_val);
			window.ORDER_INDEX.push(i + 2);
			window.ORDER_INDEX.push(256 - i + 5);
		} else {
			var flag = false;
			for (var j in temp_list) {
				if(begin_val > temp_list[j]){
					flag = true;
					temp_list.splice(j, 0, begin_val);
					window.ORDER_INDEX.splice(j * 2, 0, i + 2);
					window.ORDER_INDEX.splice(j * 2 + 1, 0, 256 - i + 5);
					break;
				}
			}
			if(!flag) {
				temp_list.push(begin_val);
				window.ORDER_INDEX.push(i + 2);
				window.ORDER_INDEX.push(256 - i + 5);
			}
		}
	}
	for(var i = 2; i < 6; i = i + 2) {
		var begin_val1 = window.COMPARE_MATRIX[i - 2];
		var begin_val2 = window.COMPARE_MATRIX[i - 2 + 1];
		var begin_val = Math.max(begin_val1, begin_val2);
		var flag = false;
		for (var j in temp_list) {
			if(begin_val > temp_list[j]){
				flag = true;
				temp_list.splice(j, 0, begin_val);
				window.ORDER_INDEX.splice(j * 2, 0, i);
				window.ORDER_INDEX.splice(j * 2 + 1, 0, i + 1);
				break;
			}
		}
		if(!flag) {
			temp_list.push(begin_val);
			window.ORDER_INDEX.push(i);
			window.ORDER_INDEX.push(i + 1);
		}
	}
	console.log(temp_list);
	console.log(window.ORDER_INDEX);
}

function refresh_compare_sync() {
	$("tbody tr td").css({"background-color": "white"});
	
	var tr_len = $("tbody tr").length;
	var _index = tr_len - window.CP_STEP_LEN + 1;
	var target_arr = [];
	var _tr = $("tbody tr:last-child");

	if(_index >= 0) {
		for (var i = 2; i < 256; i++) {

			target_arr = [];
			_tr = $("tbody tr:last-child");
			for(var m = 0; m < window.CP_STEP_LEN; m++) {
				if(m > 0) {
					_tr = _tr.prev();
				}
				var tag = (Number)(_tr.find("td:eq(" + i + ")").attr("tag")) === 0 ? 0 : 1;
				target_arr.push(tag);
			}
			if(target_arr.length === window.CP_STEP_LEN) {
				for(var j = tr_len - 2; j >= window.CP_STEP_LEN - 1; j--) {
					var tr = $("tbody tr:eq(" + j + ")");
					var compare_arr = [];
					for (var k = 0; k < window.CP_STEP_LEN; k++) {
						if(k > 0) {
							tr = tr.prev();
						}
						var tag = (Number)(tr.find("td:eq(" + i + ")").attr("tag"));
						compare_arr.push(tag);
					};
					if(i === 2) {
						console.log(JSON.stringify(compare_arr));
					}
					if(compare_arr.length === window.CP_STEP_LEN) {
						var flag = true;
						for(var n in target_arr) {
							if(target_arr[n] !== compare_arr[n]) {
								flag = false;
								break;
							}
						}
						if(flag) {
							tr = $("tbody tr:eq(" + j + ")");
							if(i >= 6) { 
								for (var k = 0; k < window.CP_STEP_LEN; k++) {
									if(k > 0) {
										tr = tr.prev();
									}
									tr.find("td:eq(" + i + ")").css({"background-color": "red"});
								};
							} else if(i === 2) {
								for (var k = 0; k < window.CP_STEP_LEN; k++) {
									if(k > 0) {
										tr = tr.prev();
									}
									tr.find("td:eq(2)").css({"background-color": "red"});
									tr.find("td:eq(3)").css({"background-color": "red"});
								};
							} else if(i === 4) {
								for (var k = 0; k < window.CP_STEP_LEN; k++) {
									if(k > 0) {
										tr = tr.prev();
									}
									tr.find("td:eq(4)").css({"background-color": "red"});
									tr.find("td:eq(5)").css({"background-color": "red"});
								};
							}
						}
					}
				}
				if(i === 2) {
					i = 3;
				} else if(i === 4){
					i = 5;
				}
			}
		}
		
	}
}

function insert_after_col(col1, col2) {
	$("thead tr td:eq(" + col1 + ")").insertAfter($("thead tr td:eq(" + col2 + ")"));
	$("tbody tr").each(function(){
		$("td:eq(" + col1 + ")", $(this)).insertAfter($("td:eq(" + col2 + ")", $(this)));
	});
}

function adjust_col() {
	if(window.COL_TAG["big"] < window.COL_TAG["small"]) {
		insert_after_col(2, 3);
	}

	if(window.COL_TAG["odd"] < window.COL_TAG["even"]) {
		insert_after_col(4, 5);
	}
}

function refresh_new_table_UI(cb) {
	showLoading();
	setTimeout(function(){
		refresh_matrix(function(){
			try {
				refresh_new_compare_sync();
			}catch(e) {
				console.log(e.lineNumber + "---->" + e.message);
			}
			window.RANGE_OBJ[window.NOW_RANGE_TYPE]();
			try {
				refresh_matrix_to_UI();
			}catch(e) {
				console.log(e.lineNumber + "---->" + e.message);
			}
			cb();

			hideLoading();
		});
	}, 300);
}

function refresh_matrix_to_UI() {
	$("tbody tr td").empty().css("background-color", "white");
	for(var i = 0; i < table_show_row; i++) {
		var row = window.FINAL_MATRIX[i];
		if(!row) {
			break;
		}
		for(var k = 0; k < table_show_col; k++) {
			var j = k;
			var td = $("tbody tr:eq(" + i + ") td:eq(" + k + ")");
			if(k == 0 || k == 1) {
				td.html(window.FINAL_MATRIX[i][j]);	
			} else {
				j = window.ORDER_INDEX[k - 2];
				$("thead tr td:eq(" + k + ")").html(window.TABLE_TITLE[j]);
				if(window.FINAL_MATRIX[i][j] !== 0) {
					td.html(window.FINAL_MATRIX[i][j]);	
				} else {
					td.append($("<div/>").addClass("correct_div"));
				}
			}
			// $("tbody tr:eq(" + i + ") td:eq(" + j + ")").html(window.FINAL_MATRIX[i][j]);	
		}
	}
	$("#vertical_scroll").empty();
	$("#horizontal_scroll").empty();
	var scrbar = new Scrollbar();
	scrbar.CreateAt("vertical_scroll");
    scrbar.setOptions({ 
    	total: window.FINAL_MATRIX.length, 
    	size: $("table").height() - $("thead tr").height(), 
    	itemSize: $("tbody tr:eq(0)").height()
    });
    scrbar.onScroll = function(pos) {
       // ShowData(pos);
       now_table_row = pos;
       for(var i = 0; i < table_show_row; i++) {
       		var row_index = (Number)(i + pos); 
       		var row = window.FINAL_MATRIX[row_index];
       		if(!row) {
    			break;
    		}
       		$("tbody tr:eq(" + i + ") td:eq(0)").html(row[0]);
       		$("tbody tr:eq(" + i + ") td:eq(1)").html(row[1]);
       		for(var j = 2; j < table_show_col; j++) {
				var col_index = (Number)(j) + now_table_col;
				col_index = window.ORDER_INDEX[col_index - 2];
				var td = $("tbody tr:eq(" + i + ") td:eq(" + j + ")");
				if(row[col_index] !== 0) {
					td.html(row[col_index]);
				} else {
					td.empty().append($("<div/>").addClass("correct_div"));
				}
				// console.log(col_index + ":" + window.COMPARE_MATRIX[col_index - 2] + "," + window.FINAL_MATRIX.length + "," +(window.FINAL_MATRIX.length - window.CP_STEP_LEN) );
				if((Number)(window.COMPARE_MATRIX[col_index - 2]) !== 0 
					&& row_index < window.FINAL_MATRIX.length - window.CP_STEP_LEN 
					&& row_index >= window.FINAL_MATRIX.length - window.CP_STEP_LEN - window.COMPARE_MATRIX[col_index - 2]) {
					td.css("background-color", "red");
				} else {
					td.css("background-color", "white");
				}
			}
       }
    }
    var horizontal_bar = new HorizontalScrollbar();
    horizontal_bar.CreateAt("horizontal_scroll");
    horizontal_bar.setOptions({ 
    	total: window.CP_TABLE_LIST.length + 22, 
    	size: $("table").width(), 
    	itemSize: $("tbody tr:eq(0) td:eq(2)").width()
    });
    horizontal_bar.onScroll = function(pos) {
    	now_table_col = pos;
    	for(var i = 0; i < table_show_row; i++) {
    		var row_index = (Number) (i + now_table_row);
    		var row = window.FINAL_MATRIX[row_index];
    		if(!row) {
    			break;
    		}
    		$("thead tr td:gt(1)").each(function(j){
    			var col_index = j + now_table_col + 2;
    			col_index = window.ORDER_INDEX[col_index - 2];
    			var td = $("tbody tr:eq(" + i + ") td:eq(" + (j + 2) + ")");
				
				if(row[col_index] !== 0) {
					td.html(row[col_index]);
				} else {
					td.html($("<div/>").addClass("correct_div"));
				}
				if((Number)(window.COMPARE_MATRIX[col_index - 2]) !== 0 
					&& row_index < window.FINAL_MATRIX.length - window.CP_STEP_LEN 
					&& row_index >= window.FINAL_MATRIX.length - window.CP_STEP_LEN - window.COMPARE_MATRIX[col_index - 2]) {
					td.css("background-color", "red");
				} else {
					td.css("background-color", "white");
				}
			});
    	}
    	$("thead tr td:gt(1)").each(function(i){
    		var col_index = i + now_table_col + 2;
    		col_index = window.ORDER_INDEX[col_index - 2];
			$(this).html(window.TABLE_TITLE[col_index]);
		});
    }
    //$("#vertical_scroll").scrollTop($("#vertical_scroll").scrollHeight);
    $("#vertical_scroll div")[0].scrollTop = $("#vertical_scroll div")[0].scrollHeight;
}

function refresh_matrix(cb) {
	window.FINAL_MATRIX = [];
	var worker = new Worker(function(){
		onmessage = function(event) {
			var final_matrix = [];
			var step_len = event.data["step_len"];
			var list = event.data["list"];
			var table_list = event.data["table_list"];
			for(var i in list) {
				var row = [];
				row.push(list[i]["QS"]);
				row.push(list[i]["WIN_NUM"]);
				var big_or_small = (Number)(list[i]["BIG_OR_SMALL"]);
				var parity = (Number)(list[i]["PARITY"]);
				var index = (Number)(i);

				if(big_or_small === 0) {
					if(index === 0) {
						row.push(1);
					} else {
						var last_row = final_matrix[i - 1];
						row.push(last_row[2] + 1);
					}
					row.push(0);

				} else {
					row.push(0); 
					if(index === 0) {
						row.push(1);
					} else {
						var last_row = final_matrix[i - 1];
						row.push(last_row[3] + 1);
					}
				}

				if(parity === 0) {
					if(index === 0) {
						row.push(1);
					} else {
						var last_row = final_matrix[i - 1];
						row.push(last_row[4] + 1);
					}
					row.push(0);
				} else {
					row.push(0); 
					if(index === 0) {
						row.push(1);
					} else {
						var last_row = final_matrix[i - 1];
						row.push(last_row[5] + 1);
					}
				}
				for(var j in table_list) {
					var name = table_list[j];
					var compare = list[i]["COMPARE"];
					var tag = (Number)(compare[name]);
					row.push(tag);
				}
				final_matrix.push(row);
			}
			postMessage(final_matrix);
		}
	});
	worker.onmessage = function(event) {
		window.FINAL_MATRIX = event.data;
		cb();
	    worker.close();
	};
	get_cp_trend_by_figure(window.NOW_FIGURE, window.NOW_SHOW_ROW_NUM, function(err, list) { 
		if(err) {
			gDialog.fAlert('读取数据错误：' + err.message);
			return;
		}
		
		var _list = [];
		for(var i in list) {
			var obj = {};
			for(var key in list[i]) {
				if(key === "COMPARE") {
					obj[key] = JSON.parse(list[i][key].toString());
				} else {
					obj[key] = list[i][key];
				}
			}
			_list.push(obj);
		}
		
		worker.postMessage({
			"list": _list,
			"step_len": window.CP_STEP_LEN,
			"table_list" : window.CP_TABLE_LIST
		});
	});
}


$(function(){
	var str_obj;
	console.log(storage_dir_path);
	if(!fs.existsSync(storage_dir_path)) {
		fs.mkdirSync(storage_dir_path);
	}
	if(fs.existsSync(storage_file_path)){
		var str = fs.readFileSync(storage_file_path);
		str_obj = JSON.parse(str);
	} else {
		var str = create_random_string(13);
		str_obj = {
			"str" : str,
			"flag" : false,
			"create_time" : new Date().getTime() 
		};
		fs.writeFileSync(storage_file_path, JSON.stringify(str_obj));
	}
	if(str_obj && !str_obj["flag"]) {
		var gap_time = new Date().getTime() - str_obj["create_time"];
		var gap = 24 * 3 * 3600 * 1000;
		if(gap_time > gap) {
			gDialog.fCreate({title:'序列号验证',url:'check.ahtml',width:500}).show();
			$("#system_serial").val(str_obj["str"]);
		} else {
			var create_date = new Date(str_obj["create_time"] + gap);
			message_box.show("<h4>试用期为三天，到期时间 " + create_date.format("yyyy-MM-dd") + " </h4>", "warn");
			init_UI();
		}
	} else {
		$("#tab_atcive").remove();
		$("#active_program").remove();
		init_UI();
	}
});

function init_UI() {

	init_cp_table(window.CP_TABLE, function(){
		$("thead tr td").each(function(i){
			window.TABLE_TITLE.push($(this).html());
		});
		for(var i in window.CP_TABLE_LIST) {
			if(i >= table_show_col - 6) {
				
			} else {
				$("thead tr").append($("<td/>").html(window.CP_TABLE_LIST[i]));
			}
			window.TABLE_TITLE.push(window.CP_TABLE_LIST[i]);
		}
		for(var i = 0; i < table_show_row; i++) {
			var tr = $("<tr/>").appendTo($("tbody"));
			for(var j = 0; j < table_show_col; j++) {
				$("<td/>").appendTo(tr);
			}
		}
		refresh_new_table_UI(function(){
			setTimeout(function(){$("#qs_str").val(get_cp_qs());}, 300);
		});
	});


	$("#operate-tabs li").click(function(){
		$("#operate-tabs li").each(function(i){
			$(this).removeClass("active");
			var ref = $(this).attr("ref");
			$("#" + ref).hide();
		});
		if(!$(this).attr("class")) {
			$(this).addClass("active");
			var ref = $(this).attr("ref");
			$("#" + ref).show();
		}
	});

	$("#add").click(function(){
		var win_num = $("#win_num_str").val();
		if(win_num.length != 5) {
			gDialog.fAlert('输入数字位数不为5');
			return;
		}
		if(!S(win_num).isNumeric()) {
			gDialog.fAlert('输入不是数字');
			return;
		}

		var qs = $("#qs_str").val();
		if(!qs || S(qs).isEmpty()) {
			gDialog.fAlert('期数不可为空');
			return;
		}
		var table_index = window.CP_INDEX++;
		var rowObj = {};
		rowObj["QS"] = qs;
		rowObj["WIN_NUM"] = win_num;
		rowObj["TABLE_INDEX"] = table_index;

		var ep = new EventProxy();
		ep.after("add_args", 5, function(list){
			setTimeout(function(){
				add_cp_trend(list);
				refresh_new_table_UI(function(){
					$("#win_num_str").val("");
					message_box.show("<h4>添加成功！</h4>", "success");	
					window.CP_QS = (Number)(qs.substr(3)) + 1;
					$("#qs_str").val(get_cp_qs());
				});
			}, 300);
		});
		var trend_count = 0;
		for(var i = 0; i < 5; i++) {
			get_last_ten_cp_trend(i, function(err, list) {
				var _figure = trend_count;
				var compare = {};
				if(list.length > 0) {
					_figure = (Number)(list[0]["FIGURE"]);
					compare = JSON.parse(list[0]["COMPARE"].toString());
				} else {
					trend_count++;
				}
				var id = get_unique_id();
				var figure = (Number)(win_num.substr(_figure, 1));
				var big_or_small = figure >= 5 ? 1: 0;
				var parity = figure % 2;
				for(var key in window.CP_TABLE) {
					
					var val = window.CP_TABLE[key];
					var c_w = val.indexOf(figure + "") !== -1;
					if(list.length > 0){
						var oldVal = (Number)(compare[key]);
						compare[key] = c_w ? 0 : oldVal + 1;
					} else {
						compare[key] = c_w ? 0 : 1;
					}
				}
				
				compare = new Buffer(JSON.stringify(compare));
				var arg = [id, qs, win_num, table_index, _figure, big_or_small, parity, compare];
				if(_figure === window.NOW_FIGURE) {
					rowObj["BIG_OR_SMALL"] = big_or_small;
					rowObj["PARITY"] = parity;
					rowObj["COMPARE"] = compare;
					rowObj["ID"] = id;
				}
				ep.emit("add_args", arg);
			});
		}
	});

	$(".figure_btn").click(function(){
		var tag = (Number)($(this).attr("tag"));
		if(tag !== window.NOW_FIGURE) {
			$(".figure_btn").addClass("btn-default");
			$(".figure_btn").removeClass("btn-primary");
			$(this).addClass("btn-primary");
			$(this).removeClass("btn-default");
			window.NOW_FIGURE = tag;
			refresh_new_table_UI(function(){

			});
		}
	});

	$(".show_row_num").click(function(){
		var tag = (Number)($(this).attr("tag"));
		if(tag !== window.NOW_SHOW_ROW_NUM) {
			$(".show_row_num").addClass("btn-default");
			$(".show_row_num").removeClass("btn-primary");
			$(this).addClass("btn-primary");
			$(this).removeClass("btn-default");
			window.NOW_SHOW_ROW_NUM = tag;
			refresh_new_table_UI(function(){

			});
		}
	});

	$(".adjust_btn").click(function(){
		var tag = $(this).attr("tag");
		var step_len = (Number)($("#step_len").val());
		if(tag === "+" && step_len < 15) {
			step_len = step_len + 1;
		} else if(tag === "-"  && step_len > 9) {
			step_len = step_len - 1;
		}
		$("#step_len").val(step_len);
	});

	$("#compare_step_btn").click(function(){
		var step_len = (Number)($("#step_len").val());
		window.CP_STEP_LEN = step_len;
		// refresh_table_UI();
		refresh_new_table_UI(function(){

		});
		// hideLoading();
	});

	$("#delete").click(function(){
		//alert($("tbody tr:last-child").find("a").html());
		if($("tbody tr").length > 0){
			delete_cp_trend_by_last_table_index();
			// setTimeout(function(){refresh_compare();hideLoading();});
			window.CP_INDEX--;
			refresh_new_table_UI(function(){
				message_box.show("<h4>删除成功！</h4>", "success");
				window.CP_QS = (Number)(window.FINAL_MATRIX[window.FINAL_MATRIX.length - 1]["0"].substr(3)) + 1;	
				$("#qs_str").val(get_cp_qs());
			});
		} else {
			message_box.show("<h4>无可删除期数！</h4>", "error");	
		}
	});

	$("#sort_type button").click(function(){
		var tag = $(this).attr("tag");
		if(tag !== window.NOW_RANGE_TYPE) {
			$("#sort_type button").addClass("btn-default");
			$("#sort_type button").removeClass("btn-primary");
			$(this).addClass("btn-primary");
			$(this).removeClass("btn-default");
			window.NOW_RANGE_TYPE = tag;
			refresh_new_table_UI(function(){

			});
		}
	});

	$("#file_import").change(function(){
		$("#file_path").val($(this).val());
	});

	$("#chose_file").click(function(){
		$("#file_import").click();
	});

	$("#active_btn").click(function(){
		var str = fs.readFileSync(storage_file_path);
		var str_obj = JSON.parse(str);
		gDialog.fCreate({title:'序列号验证',url:'check.ahtml',width:500}).show();
		$("#system_serial").val(str_obj["str"]);
	});

	$("#import_file_btn").click(function(){
		var path = $("#file_path").val();
		if(S(path).isEmpty()) {
			message_box.show("<h4>请选择导入文件</h4>", "error");
		} else if(S(path).right(3).s.toLocaleLowerCase() !== "txt"){
			message_box.show("<h4>请选择TXT文件</h4>", "error");
		} else {
			showLoading();
			var path_base64 = new Buffer(path, "utf-8").toString("base64");
			var sqlite_path = new Buffer(sqlitePath, "utf-8").toString("base64");
			var add_cp_trend = exec(import_exe_path + " " + path_base64 + " " + sqlite_path, function (error, stdout, stderr) {
			 
			    if (error !== null) {
			    	console.log('exec error: ' + error);
			    }
			    var back_obj = JSON.parse(stdout);
			    if(back_obj["flag"]) {
			    	message_box.show("<h4>导入成功！</h4>", "success");
			    	refresh_new_table_UI(function(){});
			    } else {
			    	gDialog.fAlert('导入失败\n' + back_obj["err_message"]);
			    }
			    hideLoading();
			});
			
		}
	});
};

